package com.changan.stumgr.controller;

import com.changan.stumgr.pojo.Student;
import com.changan.stumgr.service.StudentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

//@ResponseBody+@Controller   返回Json格式
//@RestController
//restful风格  rest风格
@Controller
public class StudentController {

    @Autowired
    private StudentService studentService;

    /**
     * 查询所有
     * @param model
     * @return
     */
    @RequestMapping("/students")
    public String list(Student student,Model model, @RequestParam(defaultValue = "1",value = "pageNum") Integer pageNum){
        if (pageNum==null&&pageNum==0){
            pageNum=1;
        }
        PageHelper.startPage(pageNum,5);
        List<Student> students = studentService.selAllStudent(student);
        PageInfo<Student> pageInfo = new PageInfo<Student>(students);
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("student",student);
        /*List<Student> students = studentService.selAllStudent();
        model.addAttribute("students",students);*/
        return "list";
    }

    /**
     * 删除信息
     * @param id
     * @return
     */
    @RequestMapping("/dateUser/{id}")
    public String delete(@PathVariable("id") Integer id){
        studentService.delStudent(id);
        return "redirect:/students";
    }

    /**
     * 添加信息
     * @param student
     * @return
     */
    @RequestMapping("/insUser")
    public String insUser(Student student){
        studentService.addStudent(student);
        return "redirect:/students";
    }

    /**
     * 跳转添加、修改页面
     * @return
     */
    @RequestMapping("/updataUser")
    @ResponseBody
    public List<Student> updataUser(Integer id){
        if (id!=null) {
            List<Student> student = studentService.findStudentById(id);
            return student;
        }else {
            List<Student> students = studentService.selAllStudent(new Student());
            return students;
        }

    }

    /**
     * 修改信息
     * @param student
     * @return
     */
    @RequestMapping("/upUser")
    public String upUser(Student student){
        studentService.updateStudent(student);
        return "redirect:/students";
    }

    @RequestMapping("")
    @ResponseBody
    public  List<Student> aaa(){
        List<Student> students = studentService.selAllStudent(new Student());
        return students;
    }
}
